<?php

// ----------------------------------------------------------------------
// zCart Shopping Cart Module for Zikula
// Based on pnCommerce 0.99
// ----------------------------------------------------------------------
// Source file:  $Source: W:\dev\common.php $
//
// Last changes from:  $Author: Floxxx $
//
// Revision:           $Revision: 0.1 $
//
// Date of revision    $Date: 6/17/2009 6:36:25 AM $
//
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------
// Purpose of this file: providing function used everywhere in the project
// ----------------------------------------------------------------------

/**
 * Generates a url with the given parameters using the standard
 * pnmodurl and if needed replaces the beginning with https or the sslpath
 * @param $Module string The modulename
 * @param $Section string section like admin or user
 * @param $Function string the function to call
 * @param $Args array the array of arguments for the Function
 * @return string the generated URL
 */
/*
function pncAdminModURL($Module, $Section, $Function, $Args=array())
{
    if (!pnModAPILoad('pncommerce', 'user'))
    {
        pnSessionSetVar('errormsg', _PNC_LOADUSERAPIFAILED);
        return false;
    }
    return pnModAPIFunc( 'pncommerce', 'user','pncModURL',
                                 array( 'Module'=>$Module,
                                            'Section'=>$Section,
                                            'Function'=>$Function,
                                            'Args'=>$Args ) );
}
*/
//Defines for properties, names are easier to read than 0,1,2
define('PNC_ITEMPROP',0);
define('PNC_CATEGORYPROP',1);
define('PNC_CONFIGPROP',2);
define('PNC_USERPROP',3);
// defines for schemes, looks redundant, but better for the understanding
define('PNC_ITEMSCHEME',0);
define('PNC_CATEGORYSCHEME',1);
define('PNC_CONFIGSCHEME',2);
define('PNC_USERSCHEME',3);

/**
 * Log
 * stub function for AddLogMessage
 */
function addlogmessage( $level = _PNC_LOG_ADMINERROR, $text = "" )
{
    if(pnModAPILoad( 'zCart', 'user' )) {
        pnModAPIFunc( 'zCart', 'user', 'AddLogMessage',
                      array( 'level' => $level,
                             'text'  => $text ) );
    }
    return;
}

/*
 * showerrorpage
 * display a simple error message showing $text
 *@param text string The error text
 */
function showerrorpage($error_text, $file="", $line=0)
{
    // we need to load one core file in order to have the language definitions
    // available
    if(!pnModLoad('zCart','admin')) {
        pnModLoad('zCart', 'user');
    }
    // add the message to the log
    addlogmessage( "", $error_text . " in file " . $file . " at line " . $line);

    $pnr =& new pnRender('zCart');
    $pnr->caching = false;
    $pnr->assign( 'shop_owneremail', pnModGetVar( 'zCart', 'Email' ) );
    $pnr->assign( 'error_text', $error_text );
    if(pnSecAuthAction(0, 'zCart::', '::', ACCESS_ADMIN)) {
        $pnr->assign( 'file', $file);
        $pnr->assign( 'line', $line);
    }
    $output = $pnr->fetch( "zCart_errorpage.html" );

    if(preg_match("/(api\.php|common\.php)$/i", $file)<>0)
    {
        // __FILE__ ends with api.php or is common.php itself
        include_once("header.php");
        echo $output;
        include_once("footer.php");
        exit;
    }
    return $output;
}

/**
 * internal debug function
 *
 */
function pncdebug($name="", $data, $die = false)
{
    if(pnSecAuthAction(0, "zCart::", "::", ACCESS_ADMIN)) {
        $type = gettype($data);
        echo "\n<!-- begin debug of $name -->\n<span style=\"color: red;\">$name ($type):";
        if(is_array($data)||is_object($data)) {
            $size = count($data);
            if($size>0) {
                echo "(size=$size entries)<pre>";
                print_r($data);
                echo "</pre>:<br />";
            } else {
                echo "empty<br />";
            }
        } else if(is_bool($data)) {
            echo ($data==true) ? "true<br />" : "false<br />";
        } else {
            echo "$data:<br />";
        }
        echo "</span><br />\n<!-- end debug of $name -->";
        if($die==true) {
            die();
        }
    }
}

/**
 * internal function
 *
 */
function sqldebug($sql)
{
    pncdebug('sql', $sql);
}

function pcssdebug( $data )
{
  if ( is_array( $data ) ) {
    echo "<pre>";
    print_r( $data );
    echo "</pre>";
  } else echo "<pre>" . $data . "</pre>";
}

/**
 * pncOpenDB
 * creates a dbconnection object and returns it to the calling function
 *
 *@params $table (sting) name of the table you want to access
 *@return array consisting:
 *@returns object dbconn obejct for use to execute sql queries
 *@returns string fully qualified tablename
 *@returns string fully qualified tablecolumnname
 *        or false on error
 */
function pncOpenDB($tablename)
{
    pnModDBInfoLoad('zCart');
    list($dbconn) = pnDBGetConn();
    $pntables = pnDBGetTables();

    if(isset($tablename)) {
        $columnname    = $tablename . '_column';
        if( !array_key_exists($tablename, $pntables) ||
            !array_key_exists($columnname, $pntables) ) {return false; }
        return array($dbconn, &$pntables[$tablename], &$pntables[$columnname]);
    }
    // table exists, now get the dbconnection object
    return array($dbconn, &$pntables);
}

/**
 * closes an db connection
 *
 *@params $resobj object as returned by $dbconn->Execute();
 *@returns nothing
 *
 */
function pncCloseDB($resobj)
{
    if(is_object($resobj)) {
        $resobj->Close();
    }
    return;
}

/**
 * pncExecuteSQL
 * executes an sql command and returns the result, shows error if necessary
 *
 *@params $dbconn object db onnection object
 *@params $sql    string the sql ommand to execute
 *@params $debug  bool   true if debug should be activated, default is false
 *@params $file   string name of the calling file, important for error reporting
 *@params $line   int    line in the calling file, important for error reorting
 *@returns object the result of $dbconn->Execute($sql)
 */
function pncExecuteSQL(&$dbconn, $sql, $file=__FILE__, $line=__LINE__, $debug=false)
{
    if(!is_object($dbconn) || !isset($sql) || empty($sql)) {
        return showerrorpage(_MODARGSERROR, $file, $line);
    }
    $dbconn->debug = $debug;
    $result = $dbconn->Execute($sql);
    $dbconn->debug = false;
    if($dbconn->ErrorNo() != 0) {
        //return showsqlerrorpage(_PNC_ERROR_CONNECT,$sql,$dbconn->ErrorNo(),$dbconn->ErrorMsg(), $file, $line);
        if(pnSecAuthAction(0, 'pnForum::', '::', ACCESS_ADMIN)) {
            return showerrorpage( pnVarPrepForDisplay(_PNC_ERROR_CONNECT) ." <br />
                                  sql  : $sql <br />
                                  code : " . $dbconn->ErrorNo() ."<br />
                                  msg  : " . $dbconn->ErrorMsg() . "<br />", $file, $line );
        } else {
            return showerrorpage( pnVarPrepForDisplay(_PNC_ERROR_CONNECT), $file, $line );
        }
    }
    return $result;
}

if(!function_exists(is_serialized)) {
    function is_serialized( $string )
    {
        if( @unserialize( $string ) == "" ) {
            return false;
        }
        return true;
    }
}

function pncloadapi($api = 'user', $file = __FILE__, $line = __LINE__)
{
    if(!pnModAPILoad('zCart', $api)) {
        return showerrorpage('unable to load pn' . $api . 'api', $file, $line);
    }
    return;
}
?>